<template>
  <div :id="containerId" class="map-container"></div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

const props = defineProps({
  address: {
    type: Object,
    required: true,
    default: () => ({
      province: '',
      city: '',
      district: '',
      detailedAddress: ''
    })
  }
});

const emit = defineEmits(['location-change']);
const containerId = ref(`map-container-${Date.now()}`);
const map = ref(null);
const marker = ref(null);
const geocoder = ref(null);

// 初始化地图
const initMap = async () => {
  try {
    // 如果已经初始化，先销毁
    if (map.value) {
      map.value.destroy();
      map.value = null;
      marker.value = null;
      geocoder.value = null;
    }

    console.log('正在初始化地图...');
    const AMap = await AMapLoader.load({
      key: '3386e6149a9ef0b34421884b8257f99f',
      version: '2.0',
      plugins: ['AMap.Geocoder']
    });

    // 创建地图实例
    map.value = new AMap.Map(containerId.value, {
      resizeEnable: true,
      zoom: 4,
      center: [116.397428, 39.90923]
    });

    // 创建标记点
    marker.value = new AMap.Marker({
      map: map.value,
      animation: "AMAP_ANIMATION_DROP"
    });

    // 创建地理编码实例
    geocoder.value = new AMap.Geocoder({
      city: "全国"
    });

    console.log('地图初始化完成');
    return true;
  } catch (error) {
    console.error('地图初始化失败:', error);
    return false;
  }
};

// 地理编码和更新位置
const updateLocation = async () => {
  try {
    if (!geocoder.value || !map.value || !marker.value) {
      console.log('地图组件未初始化，正在重新初始化...');
      const success = await initMap();
      if (!success) {
        console.error('地图初始化失败');
        return;
      }
    }

    const { province, city, district, detailedAddress } = props.address;
    console.log('当前地址信息:', { province, city, district, detailedAddress });

    // 构建搜索地址
    const addressParts = [];
    if (province) addressParts.push(province);
    if (city) addressParts.push(city);
    if (district) addressParts.push(district);
    if (detailedAddress) addressParts.push(detailedAddress);

    const searchAddress = addressParts.join('');
    console.log('构建的搜索地址:', searchAddress);

    if (!searchAddress) {
      console.log('没有可用的地址信息，使用默认位置');
      map.value.setCenter([116.397428, 39.90923]);
      map.value.setZoom(4);
      return;
    }

    // 地理编码查询
    const result = await new Promise((resolve, reject) => {
      geocoder.value.getLocation(searchAddress, (status, result) => {
        console.log('地理编码状态:', status);
        console.log('地理编码结果:', result);
        
        if (status === 'complete' && result.geocodes && result.geocodes.length > 0) {
          resolve(result.geocodes[0]);
        } else {
          reject(new Error(`地理编码失败: ${status}`));
        }
      });
    });

    if (!result || !result.location) {
      throw new Error('无效的地理编码结果');
    }

    // 设置缩放级别
    let zoom = 4;
    if (detailedAddress) {
      zoom = 17;
    } else if (district) {
      zoom = 12;
    } else if (city) {
      zoom = 9;
    } else if (province) {
      zoom = 6;
    }

    const position = [result.location.lng, result.location.lat];
    console.log('设置地图位置:', position, '缩放级别:', zoom);

    // 更新地图视图
    map.value.setCenter(position);
    map.value.setZoom(zoom);
    marker.value.setPosition(position);

    // 发送位置变化事件
    emit('location-change', {
      lng: result.location.lng,
      lat: result.location.lat,
      address: searchAddress,
      formattedAddress: result.formattedAddress
    });

  } catch (error) {
    console.error('更新地图位置失败:', error);
    // 发生错误时重置到默认视图
    if (map.value) {
      map.value.setCenter([116.397428, 39.90923]);
      map.value.setZoom(4);
    }
  }
};

// 监听地址变化
watch(() => props.address, (newAddress) => {
  console.log('地址发生变化:', newAddress);
  if (newAddress && (newAddress.province || newAddress.city || newAddress.district || newAddress.detailedAddress)) {
    updateLocation();
  }
}, { deep: true, immediate: true });

// 组件挂载时初始化地图
onMounted(async () => {
  console.log('组件挂载，初始化地图...');
  await initMap();
  if (props.address && props.address.province) {
    await updateLocation();
  }
});

// 组件卸载时清理资源
onUnmounted(() => {
  if (map.value) {
    map.value.destroy();
    map.value = null;
    marker.value = null;
    geocoder.value = null;
  }
});

// 暴露方法给父组件
defineExpose({
  updateLocation
});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  min-height: 400px;
}
</style>
